// pages/mallModule/invite/invite.js
const memberService = require('../../../api/memberService.js')
const smsService = require('../../../api/smsService.js')
const wxaUserService = require('../../../api/wxaUserService.js')
const auth = require('../../../utils/auth.js')

//获取应用实例
const app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    modal: false,
    mobile: '',
    captcha: '',
    getCodeBtn: "获取验证码",
    getCodeBgColor: '#d0aa86',
    prompt: false,
    entrance: 'inviter', //inviter 邀请人 invitee 被邀请人  success 
    inviteStatus: 'new', //  fail new again success 二次进入
    marginTop: '270rpx',
    marginBottom: '0rpx',
    paddingBottom: '0',
    hasUserInfo: false,
    sceneArray: [],
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    member: {},
  },
  clickActivity: function () {
    if (this.data.modal) {
      this.setData({
        modal: false
      })
    } else {
      this.setData({
        modal: true
      })
    }
  },
  clickActivityBody: function () {

  },
  clickPrompt: function () {
    if (this.data.prompt) {
      this.setData({
        prompt: false
      })
    } else {
      this.setData({
        prompt: true
      })
    }
  },
  clickPromptBody: function () {

  },
  bindMobileInput: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  bindcaptchaInput: function (e) {
    this.setData({
      captcha: e.detail.value
    })
  },
  handleBindFocus: function () {
    this.setData({
      marginBottom: '-336rpx'
    })
  },
  handleBindBlur: function () {
    this.setData({
      marginBottom: '0'
    })
  },
  getCaptcha: function () {
    if (this.checkMobile() && this.data.getCodeBgColor === '#d0aa86') {
      var seconds = 60;
      var self = this;
      this.setData({
        getCodeBgColor: '#bbb',
        getCodeBtn: seconds + 's'
      })
      var time = setInterval(function () {
        seconds--;
        self.setData({
          getCodeBtn: seconds + 's'
        })
        if (seconds <= 0) {
          self.setData({
            getCodeBtn: '获取验证码',
            getCodeBgColor: '#d0aa86'
          })
          clearInterval(time)
        }
      }, 1000)
      smsService.sendSms(this.data.mobile).then(res => {
        console.log(res)
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  checkMobile: function () {
    let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
    if (!this.data.mobile) {
      wx.showToast({
        title: "请填写手机号",
        icon: 'none',
        duration: 2000
      })
      return false;
    } else if (!reg.test(this.data.mobile)) {
      wx.showToast({
        title: "请填写正确的手机号",
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      return true;
    }
  },
  checkCaptcha: function () {
    if (!this.data.captcha) {
      wx.showToast({
        title: "请填写验证码",
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      return true;
    }
  },
  /**
   * 绑定用户手机号
   */
  bindMobile: function () {
    console.log(2)
    const that = this
    const shareArray = that.data.sceneArray
    if (this.checkMobile() && this.checkCaptcha()) {
      let postData = {
        captcha: that.data.captcha,
        inviteeMobile: that.data.mobile,
        sourceType: 'WX_XCX'
      }
      if (that.options.type === 'member') {
        postData = {
          ...postData,
          introducerId: that.options.shareId
        }
      } else if (that.options.type === 'user') {
        postData = {
          ...postData,
          introduceUserId: that.options.shareId
        }
      } else if (that.options.scene) {
        if (shareArray[0] === 'user') {
          postData = {
            ...postData,
            introduceUserId: shareArray[1]
          }
        } else if (shareArray[0] === 'store') {
          postData = {
            ...postData,
            introduceStoreId: shareArray[1]
          }
        }
      }
      memberService.invite(postData).then(res => {
        console.log(res)
        // 操作成功
        if (app.globalData.userInfo && app.globalData.userInfo.member) {
          // 绑定手机号
          wxaUserService.bindMobile(that.data.mobile, that.data.captcha).then(res => {
            console.log(res)
            wxaUserService.login().then(res => {
              console.log(res)
              if (res.member) {
                wx.setStorage({
                  key: "wj_member",
                  data: res.member
                })
              } else { }
            })
          })
        }
        that.setData({
          entrance: 'success',
          inviteStatus: 'success',
        })
      }).catch(err => {
        if (err.message === '您已经是会员用户，可以直接去下单了') {
          that.setData({
            prompt: true,
            inviteStatus: 'again',
          })
        } else if (err.message === '您已经被邀请，请您注册会员') {
          that.setData({
            prompt: true,
            inviteStatus: 'normal',
          })
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  /**
   * 获取用户信息
   */
  getUserInfo: function (e) {
    console.log(e)
    const that = this
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      wx.setStorage({
        key: "wj_userInfo",
        data: e.detail.userInfo
      })
      wxaUserService.login().then(res => {
        console.log(res)
        auth.setUser(res)
        app.globalData.userInfo = res
        if (res.member) {
          wx.setStorage({
            key: "wj_member",
            data: res.member
          })
        } else { }
      })
    } else { }
  },
  // 立即使用
  toIndex: function () {
    wx.switchTab({
      url: '../my/my'
    })
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    console.log(options)
    if (options.type) {
      this.setData({
        entrance: 'invitee',
        marginTop: '360rpx'
      })
    } else if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      var sceneArray = scene.split(',');
      console.log(sceneArray)
      this.setData({
        entrance: 'invitee',
        marginTop: '360rpx',
        sceneArray: sceneArray
      })
    } else {
      wx.getStorage({
        key: 'wj_member',
        success: function (res) {
          that.setData({
            member: res.data
          })
        }
      })
      if (app.globalData.userInfo) {
        this.setData({
          hasUserInfo: true
        })
        if (!app.globalData.userInfo.member) {
          this.setData({
            hasUserInfo: false
          })
        }
      }
    }
    if (that.options.mobile && that.options.mobile != '' && that.options.mobile != undefined) {
      const mobile = that.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) { }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  toShare: function () {
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '您还未授权登陆，请登陆后再邀请好友哦~',
        icon: 'none',
        duration: 2000
      })
    } else {
      if (!app.globalData.userInfo.member) {
        wx.showToast({
          title: '您还不是会员，请先绑定手机号码成为会员~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const login = this.checkAuth()
    if (login) {
      var shareId = ''
      if (res.from === 'button') {
        // 来自页面内转发按钮
        console.log(res.target)
        shareId = this.data.member.id
      }
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/invite/invite?type=member&shareId=' + shareId + '&mobile=' + shareId
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/index/index/index'
      }
    }
  }
})